import common from "@/utils/common"
import store from "@/store/index"

function fetchApi(path, method, data = {}) {
    let { responseType = "", headers = { "Content-Type": "application/json;charset=UTF-8" }, ...params } = data
    let token = uni.getStorageSync("token")
    if (token) {
        headers["Authorization"] = `Bearer ${token}`
    }
    let url = ""
    //#ifdef H5
    url = `${process.env.VUE_APP_BASE_URL}${path}`
    //#endif
    //#ifndef H5
    url = `${process.env.VUE_APP_MPWX_URL}${path}`
    //#endif
    return new Promise((resolve, reject) => {
        if (headers["Content-Type"].includes("multipart/form-data")) {
            uni.uploadFile({
                url,
                method,
                filePath: params.data,
                name: "file",
                header: {
                    token
                },
                success: async res => {
                    if (res.statusCode === 200 && JSON.parse(res.data).code === 0) {
                        resolve(JSON.parse(res.data).data)
                    } else {
                        reject(res)
                    }
                },
                fail: err => {
                    uni.hideLoading()
                    reject(err)
                }
            })
        } else {
            uni.request({
                url,
                method,
                data: params,
                header: headers,
                success: async res => {
                    if (res.statusCode === 200) {
                        if (responseType === "arraybuffer") {
                            return resolve(res.data)
                        }
                        if (res.data.code === 0) {
                            return resolve(res.data.data)
                        }
                        //token异常重新登录
                        if (res.data.code === 401) {
                            store.commit("resetLogin")
                            uni.reLaunch({ url: "/pages/login/index" })
                        }
                        common.showToast(res.data.msg)
                        return reject(res.data)
                    } else if (res.statusCode === 400) {
                        common.showToast(res.data.msg)
                    }
                    return reject(res.data)
                },
                fail: err => {
                    uni.hideLoading()
                    store.commit("setNetworkStatus", true)
                    reject(err)
                }
            })
        }
    })
}
export default fetchApi
